package foundation.fileUtil;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import foundation.dbUtil.DBUtil;

public class XMLmodifyUtil {

	public static HashMap<String,String> vmtypeHashMap = null;
	public static String getXmlValue(String value){
		 String path = FileNameUtil.getPrjPath();
		 File xmlFile = new File("/root/git/cases/other cases/MiCforJSS-2tier/space4cloud/statistics.xml");
	        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder dBuilder;
	        while(true){
	        	if (xmlFile.exists()) {
					break;
				}
	        	try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        try {
	            dBuilder = dbFactory.newDocumentBuilder();
	            Document doc = dBuilder.parse(xmlFile);
	            doc.getDocumentElement().normalize();

	            return  getRest(doc,value);
	        } catch (SAXException | ParserConfigurationException | IOException e1) {
	            e1.printStackTrace();
	        }
	        
	        return null;
	} 
	
	
	static String getRest(Document doc,String value){
		String rest = "";
		NodeList employees = doc.getElementsByTagName("SolutionMultiResult");
        Element emp = null;
        emp = (Element) employees.item(0);
        rest= emp.getAttribute(value);
        
        return rest;
	}
	
    public static void modifyfile(List<StringBuffer> codes) {
    	String path = FileNameUtil.getPrjPath();
    	System.out.println(path);
        File xmlFile = new File(path+"demo/mic/runFiles/resultFiles/runtime.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();

            String vmProviderNB = codes.get(0).toString().trim();
            String propertiFielPathString = "/root/git/SAOpt4CA/SAOpt4CA/demo/mic/cfgFiles/vmType.propeties";
            String[] VMtype = getFromProperties(propertiFielPathString,vmProviderNB);
            
            //update provider value
            updateProvider(doc, VMtype[0].trim());

            updateServiceType(doc,VMtype[2].trim());
            updateResourceSizeID(doc,VMtype[3].trim());
            String[] number = new String[codes.size()-1];
            for (int i = 0; i < number.length; i++) {
				number[i]=codes.get(i+1).toString().trim();
			}
            updateVMNumber(doc, number);
            
            //write the updated document to file or console
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(path+"demo/mic/runFiles/resultFiles/runtime.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");

        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }
    
    private static void updateServiceType(Document doc, String serviceType) {
    	 NodeList employees = doc.getElementsByTagName("cloudElement");
         Element emp = null;
         //loop for each employee
         for(int i=0; i<employees.getLength();i++){
             emp = (Element) employees.item(i);
                 emp.setAttribute("serviceName", serviceType);
         }
	}


	public static String[] getFromProperties(String path,String vmProviderNB){
    	PropFileUtil propFileUtil = PropFileUtil.getInstance(path);
    	String vmtypeString = propFileUtil.getParameterValue(vmProviderNB);
    	return vmtypeString.split("%");
    }

    private static void addElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;

        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Element salaryElement = doc.createElement("salary");
            salaryElement.appendChild(doc.createTextNode("10000"));
            emp.appendChild(salaryElement);
        }
    }

    private static void deleteElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node genderNode = emp.getElementsByTagName("gender").item(0);
            emp.removeChild(genderNode);
        }

    }

    private static void updateResourceSizeID(Document doc,String resourceSizeID) {
        NodeList employees = doc.getElementsByTagName("cloudElement");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node name = emp.getElementsByTagName("resourceSizeID").item(0).getFirstChild();
            name.setNodeValue(resourceSizeID);
        }
    }

    private static void updateProvider(Document doc,String provider) {
        NodeList employees = doc.getElementsByTagName("resourceContainer");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
                emp.setAttribute("provider", provider);
        }
    }
    
    private static void updateVMNumber(Document doc,String[] number) {
        NodeList employees = doc.getElementsByTagName("replicaElement");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
                emp.setAttribute("value", number[i]);
        }
    }

}
